 package com.coolgor.axnut.web.mdmis;

import org.springframework.stereotype.Controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.coolgor.axnut.util.AddressResolutionUtil;
import com.coolgor.axnut.util.BarcodeUtil;
import com.coolgor.axnut.util.HttpServletRequestUtil;
import com.coolgor.axnut.util.PathUtil;
import com.coolgor.axnut.dto.mdmis.DeliverInfoExecution;
import com.coolgor.axnut.dto.mdmis.MDMISOperationTraceExecution;
import com.coolgor.axnut.dto.mdmis.PolicyExecution;
import com.coolgor.axnut.entity.auth.LocalUser;
import com.coolgor.axnut.entity.auth.Role;
import com.coolgor.axnut.entity.mdmis.DeliverInfo;
import com.coolgor.axnut.entity.mdmis.DeliverInfoCondition;
import com.coolgor.axnut.entity.mdmis.MDMISOperationTrace;
import com.coolgor.axnut.entity.mdmis.Policy;
import com.coolgor.axnut.entity.mdmis.PolicyCondition;
import com.coolgor.axnut.enums.mdmis.PolicyStatusEnum;
import com.coolgor.axnut.enums.mdmis.DeliverInfoOperationStateEnum;
import com.coolgor.axnut.enums.mdmis.PolicyOperationStateEnum;
import com.coolgor.axnut.service.mdmis.DeliverInfoService;
import com.coolgor.axnut.service.mdmis.MDMISOperationTraceService;
import com.coolgor.axnut.service.mdmis.PolicyService;


@Controller
@RequestMapping(value="mdmis", method={RequestMethod.GET,RequestMethod.POST})
public class DeliverInfoController {
	@Autowired
	private PolicyService policyService;
	@Autowired
	private DeliverInfoService deliverInfoService;
	@Autowired
	private MDMISOperationTraceService operationTraceService;
	
	@RequestMapping(value = "/matchDeliverNo", method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	private Map<String, Object> matchDeliverNo(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		String idString = HttpServletRequestUtil.getString(request, "ids");
		List<DeliverInfo> importSuccessList = new ArrayList<DeliverInfo>();
		DeliverInfo deliverInfoCondition ;
		DeliverInfo deliverInfoTemp ;	
		DeliverInfo deliverInfoImport ;	
		DeliverInfoExecution deliverInfoExe;
		DeliverInfoExecution flag;
		/** 暂时不采用生成条形码图片文件的方式
		String deliverNoBarcode;
		String returnNoBarcode;		
		*/
	    if (!"".equals(idString) && idString!=null) {
	    	String[] recordIDs = idString.split(",");
	    	//循环操作每一张保单
	    	for (int i=0; i<recordIDs.length; i++) {
	    		deliverInfoTemp = deliverInfoService.getTempDeliverInfo(Long.valueOf(recordIDs[i]));
	    		if (deliverInfoTemp!=null) {
	    			//如果 这个recordID是可以获取到对应的快递信息的
	    			deliverInfoCondition = new DeliverInfo();
		    		deliverInfoCondition.setTelephone(deliverInfoTemp.getTelephone());
		    		deliverInfoCondition.setDeliverTime(deliverInfoTemp.getDeliverTime());
		    		deliverInfoExe = deliverInfoService.getDeliverInfoList(deliverInfoCondition, 0, 99);
		    		if (deliverInfoExe.getState()==DeliverInfoOperationStateEnum.SUCCESS.getState()) {
	    				flag = null ;
		    			for (int j = 0; j<deliverInfoExe.getCount(); j++) {
		    				deliverInfoImport = deliverInfoExe.getList().get(j);
		    				deliverInfoImport.setDeliverCompany(deliverInfoTemp.getDeliverCompany());
		    				deliverInfoImport.setDeliverNo(deliverInfoTemp.getDeliverNo());
		    				deliverInfoImport.setReturnNo(deliverInfoTemp.getReturnNo());
		    				/** 暂时不采用生成条形码图片文件的方式
		    				//构建寄出单号及回单号条形码的文件名
		    				deliverNoBarcode = PathUtil.getBarcodePath()+deliverInfoImport.getDeliverNo()+".png";
		    				returnNoBarcode = PathUtil.getBarcodePath()+deliverInfoImport.getReturnNo()+".png";
		    				//判断路径是否存在，如果不存咋则创建
		    				PathUtil.makeDirPath(PathUtil.getBarcodePath());
		    				//生成条形码
		    				BarcodeUtil.generateFile(deliverInfoTemp.getDeliverNo(), deliverNoBarcode);
		    				BarcodeUtil.generateFile(deliverInfoTemp.getReturnNo(), returnNoBarcode);
		    				*/
		    				if (deliverInfoImport.getDeliverInfo() == null) {
		    					deliverInfoImport.setDeliverInfo(deliverInfoTemp.getDeliverInfo());
		    				} else {
		    					deliverInfoImport.setDeliverInfo(deliverInfoImport.getDeliverInfo()+"|"+deliverInfoTemp.getDeliverInfo());
		    				}
		    				if (deliverInfoImport.getRemark() == null) {
			    				deliverInfoImport.setRemark(deliverInfoTemp.getRemark());	
		    				} else {
			    				deliverInfoImport.setRemark(deliverInfoImport.getRemark()+"|"+deliverInfoTemp.getRemark());		    					
		    				}
		    				flag = deliverInfoService.modifyDeliverInfo(deliverInfoImport);
		    			}
			    		if (flag.getState()==DeliverInfoOperationStateEnum.SUCCESS.getState()) {
				    		importSuccessList.add(deliverInfoTemp);
			    		}
		    		}
	    		}
	    	}
	    	flag = null;
	    	flag = deliverInfoService.batchRemoveTempDeliverInfo(importSuccessList);
	    	if (flag.getState()==DeliverInfoOperationStateEnum.SUCCESS.getState()) {
				modelMap.put("success", true);
				modelMap.put("total", importSuccessList.size());
    		} else {
    			modelMap.put("success", false);
    			modelMap.put("errMsg", "clear import pool error!");
    		}
	    } else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "Empty Parameter");
		}
		return modelMap;
	}	
	
	@RequestMapping(value = "/getDeliverInfoImportPool", method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	private Map<String, Object> getDeliverInfoImportPool(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
	    int page = HttpServletRequestUtil.getInt(request, "page");
	    int pageSize = HttpServletRequestUtil.getInt(request, "rows");
	    DeliverInfo deliverInfoCondition = new DeliverInfo();
	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	    String deliverTime = HttpServletRequestUtil.getString(request, "deliverTime");
	    if (!"".equals(deliverTime) && deliverTime!=null) {
	    	try {
	    		deliverInfoCondition.setDeliverTime(sdf.parse(deliverTime));
			} catch (ParseException e) {
				e.printStackTrace();
			}
	    }
	    DeliverInfoExecution exe = deliverInfoService.getTempDeliverInfoList(deliverInfoCondition, page, pageSize);
		if (null != exe ) {
			try {
				modelMap.put("total",exe.getCount());
				modelMap.put("rows",exe.getList());
				modelMap.put("success", true);
			} catch (Exception e) {
				modelMap.put("success", false);
				modelMap.put("errMsg", e.toString());
			}
		} else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "Empty List");
		}
		return modelMap;
	}
	
	@RequestMapping(value = "/removeTempDeliverInfo", method={RequestMethod.POST})
	@ResponseBody
	private Map<String, Object> removeTempDeliverInfo(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		String idString = HttpServletRequestUtil.getString(request, "ids");
		List<DeliverInfo> list = new ArrayList<DeliverInfo>();
		DeliverInfo deliverInfo ;
	    if (!"".equals(idString) && idString!=null) {
	    	String[] ids = idString.split(",");
	    	for (int i=0; i<ids.length; i++) {
	    		deliverInfo = new DeliverInfo();
	    		deliverInfo.setRecordID(Long.valueOf(ids[i]));
	    		list.add(deliverInfo);
	    	}
	    	DeliverInfoExecution exe = deliverInfoService.batchRemoveTempDeliverInfo(list);
	    	if (null != exe ) {
				try {
					modelMap.put("total",exe.getCount());
					modelMap.put("success", true);
				} catch (Exception e) {
					modelMap.put("success", false);
					modelMap.put("errMsg", e.toString());
				}
			} else {
				modelMap.put("success", false);
				modelMap.put("errMsg", "Empty List");
			}
	    } else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "Empty Parameter");
		}
		return modelMap;
	}	
	
	@RequestMapping(value = "/getDeliverInfoList", method={RequestMethod.POST})
	@ResponseBody
	private Map<String, Object> getDeliverInfoList(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
	    int page = HttpServletRequestUtil.getInt(request, "page");
	    int pageSize = HttpServletRequestUtil.getInt(request, "rows");
	    DeliverInfo deliverInfoCondition = new DeliverInfo();
	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	    String deliverTime = HttpServletRequestUtil.getString(request, "deliverTime");
	    if (!"".equals(deliverTime) && deliverTime!=null) {
	    	try {
	    		deliverInfoCondition.setDeliverTime(sdf.parse(deliverTime));
			} catch (ParseException e) {
				e.printStackTrace();
			}
	    }
	    String insureNo = HttpServletRequestUtil.getString(request, "insure_no");
	    if (!"".equals(insureNo) && insureNo!=null) {
	    	deliverInfoCondition.setInsureNo(insureNo);
	    }
	    DeliverInfoExecution exe = deliverInfoService.getDeliverInfoList(deliverInfoCondition, page, pageSize);
		if (null != exe ) {
			try {
				modelMap.put("total",exe.getCount());
				modelMap.put("rows",exe.getList());
				modelMap.put("success", true);
			} catch (Exception e) {
				modelMap.put("success", false);
				modelMap.put("errMsg", e.toString());
			}
		} else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "Empty List");
		}
		return modelMap;
	}
	
	@RequestMapping(value = "/getDeliverInfoListByCondition", method={RequestMethod.POST})
	@ResponseBody
	private Map<String, Object> getDeliverInfoListByCondition(@RequestBody DeliverInfoCondition deliverInfoCondition,HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
	    int page = deliverInfoCondition.getPage();//HttpServletRequestUtil.getInt(request, "page");
	    int pageSize = deliverInfoCondition.getRows();//HttpServletRequestUtil.getInt(request, "rows");
	    if ("".equals(deliverInfoCondition.getInsureNo())) deliverInfoCondition.setInsureNo(null);
	    if ("".equals(deliverInfoCondition.getRecipient())) deliverInfoCondition.setRecipient(null);
	    if ("".equals(deliverInfoCondition.getTelephone())) deliverInfoCondition.setTelephone(null);
	    if ("".equals(deliverInfoCondition.getAddress())) deliverInfoCondition.setAddress(null);
	    if ("".equals(deliverInfoCondition.getDeliverNo())) deliverInfoCondition.setDeliverNo(null);
	    if ("".equals(deliverInfoCondition.getDeliverInfo())) deliverInfoCondition.setDeliverInfo(null);
	    if ("".equals(deliverInfoCondition.getRemark())) deliverInfoCondition.setRemark(null);
		DeliverInfoExecution exe = deliverInfoService.getDeliverInfoList(deliverInfoCondition, page, pageSize);
		if (null != exe ) {
			try {
				modelMap.put("total",exe.getCount());
				modelMap.put("rows",exe.getList());
				modelMap.put("success", true);
			} catch (Exception e) {
				modelMap.put("success", false);
				modelMap.put("errMsg", e.toString());
			}
		} else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "Empty List");
		}
		return modelMap;
	}		
	
	@RequestMapping(value = "/removeDeliverInfo", method={RequestMethod.POST})
	@ResponseBody
	private Map<String, Object> removeDeliverInfo(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		String idString = HttpServletRequestUtil.getString(request, "ids");
		List<DeliverInfo> list = new ArrayList<DeliverInfo>();
		DeliverInfo deliverInfo ;
	    if (!"".equals(idString) && idString!=null) {
	    	String[] ids = idString.split(",");
	    	for (int i=0; i<ids.length; i++) {
	    		deliverInfo = new DeliverInfo();
	    		deliverInfo.setRecordID(Long.valueOf(ids[i]));
	    		list.add(deliverInfo);
	    	}
	    	DeliverInfoExecution exe = deliverInfoService.batchRemoveDeliverInfo(list);
	    	if (null != exe ) {
				try {
					modelMap.put("total",exe.getCount());
					modelMap.put("success", true);
				} catch (Exception e) {
					modelMap.put("success", false);
					modelMap.put("errMsg", e.toString());
				}
			} else {
				modelMap.put("success", false);
				modelMap.put("errMsg", "Empty List");
			}
	    } else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "Empty Parameter");
		}
    	//关键操作，需要记录
    	if ((boolean) modelMap.get("success")) {
		    this.markOperation(request, "删除配送记录", idString, "操作成功", null);
    	} else {
		    this.markOperation(request, "删除配送记录", idString, (String)modelMap.get("errMsg"), null);
    	}
		return modelMap;
	}	
	
	/**
	 * 特殊配送登记
	 * 这个方法用于将保单寄出
	 * @param request,insure_no
	 * @return
	 */
	@RequestMapping(value = "/addDeliverInfo", method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	private Map<String, Object> addDeliverInfo(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		PolicyExecution policyExe = null;
		DeliverInfoExecution deliverInfoExe = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	    String insureNo = HttpServletRequestUtil.getString(request, "insure_no");
	    if (!"".equals(insureNo) && insureNo!=null) {
	    	Policy policy = policyService.getPolicy(insureNo);
	    	DeliverInfo deliverInfo = new DeliverInfo();
	    	if (policy!=null) {
	    		//判断这个保单今天是否有寄出记录
	    		deliverInfo.setInsureNo(policy.getInsureNo());
	    		deliverInfo.setDeliverTime(new Date());
	    		deliverInfoExe = deliverInfoService.getDeliverInfoList(deliverInfo,0,100);
	    		if (deliverInfoExe.getCount()>0) {
	    			//如果配送信息中已经存在这张保单今天的寄出信息，直接返回失败信息，不予插入。
	    			modelMap.put("success", false);
	    			modelMap.put("errTab", "stop");
	    			modelMap.put("errMsg", "该保单在今日已存在寄出信息！本次操作失败！");
	    	    	return modelMap;
	    		}
	    		//修改保单的状态以及保单的寄送次数
	    		policy.setStatus(Integer.valueOf(PolicyStatusEnum.SEND.getState()));
	    		policy.setStatusInfo(PolicyStatusEnum.SEND.getStateInfo());
	    		if (policy.getDeliverCount()==null) {
	    			policy.setDeliverCount(1);
	    		} else {
	    			policy.setDeliverCount(policy.getDeliverCount()+1);
	    		} 
	    		//构建保单的快递信息
	    		deliverInfo.setInsureNo(policy.getInsureNo());
	    		//从request中获取到寄送日期
	    	    String deliverTime = HttpServletRequestUtil.getString(request, "deliver_time");
	    	    if (!"".equals(deliverTime) && deliverTime!=null) {
	    	    	try {
	    	    		deliverInfo.setDeliverTime(sdf.parse(deliverTime));
	    			} catch (ParseException e) {
	    				e.printStackTrace();
	    			}
	    	    }
	    		//记录是本保单第几次寄送
	    	    deliverInfo.setDeliverTimes(policy.getDeliverCount());
	    		//收件地址
	    	    String address = HttpServletRequestUtil.getString(request, "address");
	    	    if (!"".equals(address) && address!=null) {
	    	    	deliverInfo.setAddress(address);
	    	    }
	    	    //收件人
	    	    String recipient = HttpServletRequestUtil.getString(request, "recipient");
	    	    if (!"".equals(recipient) && recipient!=null) {
	    	    	deliverInfo.setRecipient(recipient);
	    	    }
	    	    //联系电话
	    	    String telephone = HttpServletRequestUtil.getString(request, "telephone");
	    	    if (!"".equals(telephone) && telephone!=null) {
		    		deliverInfo.setTelephone(telephone);
	    	    }	
	    	    //寄出单号
	    	    String deliverNo = HttpServletRequestUtil.getString(request, "deliver_no");
	    	    if (!"".equals(deliverNo) && deliverNo!=null) {
		    		deliverInfo.setDeliverNo(deliverNo);
	    	    }		
	    	    //返回单号
	    	    String returnNo = HttpServletRequestUtil.getString(request, "return_no");
	    	    if (!"".equals(returnNo) && returnNo!=null) {
		    		deliverInfo.setReturnNo(returnNo);
	    	    }	 		
	    	    //快递公司
	    	    String deliver_company = HttpServletRequestUtil.getString(request, "deliver_company");
	    	    if (!"".equals(deliver_company) && deliver_company!=null) {
		    		deliverInfo.setDeliverCompany(deliver_company);
	    	    }	   		
	    	    //备注快递信息
	    	    String remark = HttpServletRequestUtil.getString(request, "remark");
	    	    if (!"".equals(remark) && remark!=null) {
		    		deliverInfo.setRemark(remark);
	    	    }	    		
	    		policyExe = policyService.modifyPolicy(policy); 
	    		deliverInfoExe = deliverInfoService.addDeliverInfo(deliverInfo);
	    		if (null != policyExe && null != deliverInfoExe) {
	    			try {
	    				modelMap.put("data",policyExe.getPolicy());
	    				modelMap.put("success", true);
	    			} catch (Exception e) {
	    				modelMap.put("success", false);
	    				modelMap.put("errMsg", e.toString());
	    			}
	    		} else {
	    			modelMap.put("success", false);
	    			modelMap.put("errMsg", "Empty List");
	    		}
	    	} else {
				modelMap.put("success", false);
				modelMap.put("errMsg", "Empty insure information");
	    	}
	    	//关键操作，需要记录
	    	if ((boolean) modelMap.get("success")) {
			    this.markOperation(request, "登记特殊寄送", deliverInfo.toString(), "操作成功", null);
	    	} else {
			    this.markOperation(request, "登记特殊寄送", deliverInfo.toString(), (String)modelMap.get("errMsg"), null);
	    	}
	    } else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "Empty insure number");
	    }	
		return modelMap;
	}	
	
	
	/**
	 * 修改保单配送信息
	 * @param request,insure_no
	 * @return
	 */
	@RequestMapping(value = "/modifyDeliverInfo", method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	private Map<String, Object> modifyDeliverInfo(@RequestBody DeliverInfo deliverInfo, HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		if (null == deliverInfo) {
			modelMap.put("success", false);
			modelMap.put("errMsg", "Empty DeliverInfo Entity!");
			return modelMap;
		}
		//更新配送信息
//		deliverInfo.setStatusInfo(PolicyStatusEnum.stateOf(policy.getStatus()).getStateInfo());
		DeliverInfoExecution exe = deliverInfoService.modifyDeliverInfo(deliverInfo);
		if (null != exe ) {
			try {
				modelMap.put("total",exe.getCount());
				modelMap.put("rows",exe.getList());
				modelMap.put("success", true);
			} catch (Exception e) {
				modelMap.put("success", false);
				modelMap.put("errMsg", e.toString());
			}
		} else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "Empty List");
		}
    	//关键操作，需要记录
    	if ((boolean) modelMap.get("success")) {
		    this.markOperation(request, "修改配送信息", deliverInfo.toString(), "操作成功", null);
    	} else {
		    this.markOperation(request, "修改配送信息", deliverInfo.toString(), (String)modelMap.get("errMsg"), null);
    	}
		return modelMap; 
	}
	
	private Boolean markOperation(HttpServletRequest request, 
									String target, 
									String operation, 
									String result, 
									String remark) {
		MDMISOperationTrace operationTrace = new MDMISOperationTrace();
		//从session中获取用户信息
	    LocalUser localUser = (LocalUser) request.getSession().getAttribute("login_user");
		// 如果没有登陆用户的信息，直接返回失败。
		if (null==localUser) return false;
	    operationTrace.setUserID(localUser.getUserID());
	    operationTrace.setUsername(localUser.getUsername());
	    operationTrace.setNameCN(localUser.getNameCN());
	    //从session中获取当前角色信息
	    Role loginRole = (Role) request.getSession().getAttribute("login_role");
		// 如果没有登陆角色的信息，创建一个空角色。
		if (null==loginRole) loginRole = new Role();
	    operationTrace.setRoleID(loginRole.getRoleID());
	    operationTrace.setRoleName(loginRole.getRoleName());
	    //从request中获取 当前操作的IP地址    
	    operationTrace.setSource(HttpServletRequestUtil.getIP(request));
	    //其它参数赋值
		operationTrace.setActionTime(new Date());
    	operationTrace.setTarget(target);
	    operationTrace.setOperation(operation);
	    operationTrace.setResult(result);
	    operationTrace.setRemark(remark);
	    MDMISOperationTraceExecution exe = operationTraceService.addOperationTrace(operationTrace);
		if (null != exe ) {
			return true;
		} else {
			return false;
		}		
	}
}
